package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.ScoreRuleConditionConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.ScoreRuleStateEnum;
import com.xbongbong.paas.enums.clazz.ConditionClass;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.log.thread.LogThreadPoolBeanConfig;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.pojo.dto.ConditionListDTO;
import com.xbongbong.paas.pojo.vo.ConditionListVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.domain.entity.LabelEntity;
import com.xbongbong.pro.domain.entity.ScoreOperationEntity;
import com.xbongbong.pro.domain.entity.ScoreRuleConditionEntity;
import com.xbongbong.pro.domain.entity.ScoreRuleEntity;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ScoreErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.score.pojo.dto.ScoreFieldConditionDTO;
import com.xbongbong.pro.score.pojo.dto.ScoreRuleAddDTO;
import com.xbongbong.pro.score.pojo.dto.ScoreRuleDeleteDTO;
import com.xbongbong.pro.score.pojo.dto.ScoreRuleDetailDTO;
import com.xbongbong.pro.score.pojo.dto.ScoreRuleEnableDTO;
import com.xbongbong.pro.score.pojo.dto.ScoreRuleListDTO;
import com.xbongbong.pro.score.pojo.dto.ScoreRuleRepeatDTO;
import com.xbongbong.pro.score.pojo.dto.ScoreRuleSaveDTO;
import com.xbongbong.pro.score.pojo.vo.ScoreRuleDetailVO;
import com.xbongbong.pro.score.pojo.vo.ScoreRuleItemVO;
import com.xbongbong.pro.score.pojo.vo.ScoreRuleListVO;
import com.xbongbong.pro.score.pojo.vo.ScoreRuleSaveVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.help.ScoreRuleHelp;
import com.xbongbong.saas.model.LabelModel;
import com.xbongbong.saas.model.ScoreRuleModel;
import com.xbongbong.saas.service.ScoreRuleService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * @author chunyang.qin
 * @version v1.0
 * @date 2020/11/4 10:35
 * @since v1.0
 */
@Service("scoreRuleService")
public class ScoreRuleServiceImpl implements ScoreRuleService {

    private static final Logger LOG = LoggerFactory.getLogger(ScoreRuleServiceImpl.class);

    @Resource
    private ScoreRuleModel scoreRuleModel;

    @Resource
    private ScoreRuleHelp scoreRuleHelp;

    @Resource
    private MongoLogHelp mongoLogHelp;

    @Resource
    private LogThreadPoolBeanConfig logThreadPoolBeanConfig;

    @Resource
    private LabelModel labelModel;

    @Resource
    private PaasFormExplainModel paasFormExplainModel;


    @Override
    public ScoreRuleListVO listScoreRule(ScoreRuleListDTO scoreRuleListDTO) throws XbbException {
        Long formId = scoreRuleListDTO.getFormId();
        Integer businessType = scoreRuleListDTO.getBusinessType();
        //业务类型校验
        scoreRuleHelp.verificationBusinessType(businessType);
        ScoreRuleListVO sonarRuleListVO = new ScoreRuleListVO();
        List<ScoreRuleItemVO> scoreRuleList = new ArrayList<>();
        Map<String, Object> params = new HashMap<>(4);
        params.put("corpid", scoreRuleListDTO.getCorpid());
        params.put("formId", formId);
        params.put("del", 0);
        List<ScoreRuleEntity> scoreRuleEntityList = scoreRuleModel.findEntitys(params);
        if(CollectionsUtil.isNotEmpty(scoreRuleEntityList)){
            ScoreRuleItemVO scoreRuleItemVO;
            for(ScoreRuleEntity scoreRuleEntity : scoreRuleEntityList ){
                scoreRuleItemVO = new ScoreRuleItemVO();
                scoreRuleItemVO.setRuleName(scoreRuleEntity.getRuleName());
                scoreRuleItemVO.setDataId(scoreRuleEntity.getId());
                scoreRuleItemVO.setEnable(scoreRuleEntity.getEnable());
                scoreRuleList.add(scoreRuleItemVO);
            }
        }
        sonarRuleListVO.setFormId(formId);
        sonarRuleListVO.setBusinessType(businessType);
        sonarRuleListVO.setScoreRuleList(scoreRuleList);
        return sonarRuleListVO;
    }

    @Override
    public ScoreRuleDetailVO getScoreRule(ScoreRuleDetailDTO scoreRuleDetailDTO) throws XbbException {
        Long dataId = scoreRuleDetailDTO.getDataId();
        String corpid = scoreRuleDetailDTO.getCorpid();
        ScoreRuleEntity scoreRuleEntity = scoreRuleModel.getByKey(dataId, corpid);
        ScoreRuleDetailVO scoreRuleDetailVO = scoreRuleHelp.packageScoreRuleDetailVO(scoreRuleEntity);
        return scoreRuleDetailVO;
    }

    @Override
    public ScoreRuleSaveVO getAddVo(ScoreRuleAddDTO scoreRuleAddDTO) throws XbbException {
        Long formId = scoreRuleAddDTO.getFormId();
        String corpid = scoreRuleAddDTO.getCorpid();
        Integer businessType = scoreRuleAddDTO.getBusinessType();
        ScoreRuleSaveVO scoreRuleSaveVO = new ScoreRuleSaveVO();
        //填充解释,设置画像评分和行为评分支持的字段
        scoreRuleHelp.setScoreExplainListForSave(scoreRuleSaveVO,corpid,formId,businessType);
        //填充操作code
        scoreRuleSaveVO.setScoreOperation(scoreRuleHelp.getScoreOperationList());
        return scoreRuleSaveVO;
    }

    @Override
    public ScoreRuleSaveVO getUpdateVo(ScoreRuleDetailDTO scoreRuleDetailDTO) throws XbbException {
        Long formId = scoreRuleDetailDTO.getFormId();
        String corpid = scoreRuleDetailDTO.getCorpid();
        Integer businessType = scoreRuleDetailDTO.getBusinessType();
        ScoreRuleSaveVO scoreRuleSaveVO = new ScoreRuleSaveVO();
        //填充解释,过滤掉不支持评分的字段。
        scoreRuleHelp.setScoreExplainListForSave(scoreRuleSaveVO,corpid,formId,businessType);
        //填充规则数据，用于回显
        ScoreRuleDetailVO scoreRule = getScoreRule(scoreRuleDetailDTO);
        BeanUtil.copyProperties(scoreRule, scoreRuleSaveVO);
        //填充操作code
        scoreRuleSaveVO.setScoreOperation(scoreRuleHelp.getScoreOperationList());
        return scoreRuleSaveVO;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseVO saveScoreRule(ScoreRuleSaveDTO scoreRuleSaveDTO) throws XbbException {
        Long dataId = scoreRuleSaveDTO.getDataId();
        Long formId = scoreRuleSaveDTO.getFormId();
        String corpid = scoreRuleSaveDTO.getCorpid();
        String newRuleName = scoreRuleSaveDTO.getRuleName();
        String loginUserName = scoreRuleSaveDTO.getLoginUserName();
        //保存常规校验
        scoreRuleHelp.verificationData(scoreRuleSaveDTO);

        ScoreRuleEntity oldScoreRuleEntity = Objects.isNull(dataId) ? null : scoreRuleModel.getByKey(dataId, corpid);

        ScoreRuleEntity newScoreRuleEntity = scoreRuleHelp.packageScoreRuleEntity(scoreRuleSaveDTO);
        Boolean isNew = Objects.isNull(dataId);
        //新增逻辑
        if(Objects.isNull(dataId)){
            //新增需要校验表单下评分规则最多10条
            List<ScoreRuleEntity> scoreRuleEntityList = scoreRuleHelp.getAllScoreRuleByFormId(formId, corpid);
            scoreRuleHelp.verificationScoreRuleTotal(scoreRuleEntityList);
            scoreRuleModel.insert(newScoreRuleEntity);
        }else {
            scoreRuleModel.update(newScoreRuleEntity);
        }

        // 评分规则日志
        //操作日志
        Runnable runnable = () -> {
            try {
                OperateTypeEnum operateTypeEnum;
                String userId = scoreRuleSaveDTO.getUserId();
                String httpHeader = scoreRuleSaveDTO.getHttpHeader();
                OperateModuleTypeEnum operateModuleTypeEnum = OperateModuleTypeEnum.SCORE_RULE_SET;
                // 行为评分权重
                Double actionScoreRate = scoreRuleSaveDTO.getActionScoreRate();
                String actionScoreRateStr = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_SET_ACTION_RATE_SCORE_RULE), String.valueOf(actionScoreRate)) + "%";
                // 画像评分权重
                Double portraitScoreRate = scoreRuleSaveDTO.getPortraitScoreRate();
                String portraitScoreRateStr = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_SET_PORTRAIT_RATE_SCORE_RULE), String.valueOf(portraitScoreRate)) + "%";
                // 画像评分
                List<ScoreFieldConditionDTO> portraitScoreRule = scoreRuleSaveDTO.getPortraitScoreRule();
                String portraitScoreRuleStr = null;
                if(CollectionsUtil.isNotEmpty(portraitScoreRule)){
                    portraitScoreRuleStr = scoreStr(formId, corpid, portraitScoreRule);
                }
                // 行为评分
                List<ScoreFieldConditionDTO> actionScoreRule = scoreRuleSaveDTO.getActionScoreRule();
                String actionScoreRuleStr = null;
                if(CollectionsUtil.isNotEmpty(actionScoreRule)){
                    actionScoreRuleStr = scoreStr(formId, corpid, actionScoreRule);
                }

                String defaultMemo = "";
                if(isNew){
                    defaultMemo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_SCORE_RULE), loginUserName, newRuleName);
                } else {
                    if(oldScoreRuleEntity != null){
                        String oldRuleName = oldScoreRuleEntity.getRuleName();
                        defaultMemo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_SCORE_RULE), loginUserName, oldRuleName, newRuleName);
                    }
                }
                StringBuilder memoStr = new StringBuilder();
                memoStr.append(defaultMemo);

                if(isNew){
                    operateTypeEnum = OperateTypeEnum.NEW;
                    // 画像
                    memoStr.append(portraitScoreRateStr);
                    if(portraitScoreRuleStr != null){
                        memoStr.append(portraitScoreRuleStr);
                    }
                    // 行为
                    memoStr.append(actionScoreRateStr);
                    if(actionScoreRuleStr != null){
                        memoStr.append(actionScoreRuleStr);
                    }
                } else {
                    operateTypeEnum = OperateTypeEnum.EDIT;
                    if(oldScoreRuleEntity != null){
                        // 画像评分权重
                        Double oldPortraitScoreRate = oldScoreRuleEntity.getPortraitScoreRate() * 100;
                        String oldPortraitScoreRateStr = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_SET_PORTRAIT_RATE_SCORE_RULE), oldPortraitScoreRate);
                        // 画像
                        BigDecimal oldPortrait = new BigDecimal(oldPortraitScoreRate);
                        BigDecimal newPortrait = new BigDecimal(portraitScoreRate);
                        int portraitFlag = newPortrait.compareTo(oldPortrait);
                        if(portraitFlag != BasicConstant.ZERO){
                            String changeCondition = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_CHANGE_USER_AUTO_DISTRIBUTION_RULE), oldPortraitScoreRateStr, portraitScoreRateStr);
                            memoStr.append(changeCondition);
                        }
                        List<ScoreFieldConditionDTO> oldPortraitScoreRule = JSONArray.parseArray(oldScoreRuleEntity.getPortraitScoreRule(), ScoreFieldConditionDTO.class);
                        oldPortraitScoreRule = oldPortraitScoreRule == null ? new ArrayList<>() : oldPortraitScoreRule;
                        if(!Objects.equals(oldPortraitScoreRule, portraitScoreRule)){
                            String oldPortraitScoreRuleStr = null;
                            if(CollectionsUtil.isNotEmpty(oldPortraitScoreRule)){
                                oldPortraitScoreRuleStr = scoreStr(formId, corpid, oldPortraitScoreRule);
                            }
                            oldPortraitScoreRuleStr = oldPortraitScoreRuleStr == null ? I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_SET_SCORE_NO_ITEM) : oldPortraitScoreRuleStr;
                            String changeCondition = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_CHANGE_USER_AUTO_DISTRIBUTION_RULE), oldPortraitScoreRuleStr, portraitScoreRuleStr);
                            memoStr.append(changeCondition);
                        }
                        // 行为评分权重
                        Double oldActionScoreRate = oldScoreRuleEntity.getActionScoreRate() * 100;
                        String oldActionScoreRateStr = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_SET_ACTION_RATE_SCORE_RULE), oldActionScoreRate);
                        // 行为
                        BigDecimal oldAction = new BigDecimal(oldActionScoreRate);
                        BigDecimal newAction = new BigDecimal(actionScoreRate);
                        int actionFlag = newAction.compareTo(oldAction);
                        if(actionFlag != BasicConstant.ZERO){
                            String changeCondition = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_CHANGE_USER_AUTO_DISTRIBUTION_RULE), oldActionScoreRateStr, actionScoreRateStr);
                            memoStr.append(changeCondition);
                        }
                        List<ScoreFieldConditionDTO> oldActionScoreRule = JSONArray.parseArray(oldScoreRuleEntity.getActionScoreRule(), ScoreFieldConditionDTO.class);
                        oldActionScoreRule = oldActionScoreRule == null ? new ArrayList<>() : oldActionScoreRule;
                        if(!Objects.equals(oldActionScoreRule, actionScoreRule)){
                            String oldActionScoreRuleStr = null;
                            if(CollectionsUtil.isNotEmpty(oldActionScoreRule)){
                                oldActionScoreRuleStr = scoreStr(formId, corpid, oldActionScoreRule);
                            }
                            oldActionScoreRuleStr = oldActionScoreRuleStr == null ? I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_SET_SCORE_NO_ITEM) : oldActionScoreRuleStr;
                            String changeCondition = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_CHANGE_USER_AUTO_DISTRIBUTION_RULE), oldActionScoreRuleStr, actionScoreRuleStr);
                            memoStr.append(changeCondition);
                        }

                    }
                }
                mongoLogHelp.buildLog(corpid, userId, loginUserName, operateModuleTypeEnum, operateTypeEnum, newScoreRuleEntity.getId().toString(), newRuleName, memoStr.toString(), httpHeader);
            } catch (XbbException e) {
                LOG.error("ScoreRuleServiceImpl saveScoreRule 异常信息{}",e.getMessage());
            }
        };
        logThreadPoolBeanConfig.sysLogThreadPool().execute(runnable);

        return new BaseVO();
    }

    /**
     * 评分规则
     * @param formId
     * @param corpid
     * @param scoreRule
     * @return
     * @throws XbbException
     */
    private String scoreStr(Long formId, String corpid, List<ScoreFieldConditionDTO> scoreRule) throws XbbException{
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
        if (Objects.isNull(paasFormExplainEntity)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains(), null);

        StringBuilder conditionStr = new StringBuilder();
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_SET_SCORE_FIELD_ITEM));
        conditionStr.append(memo);
        if(CollectionsUtil.isNotEmpty(scoreRule)){
            for(ScoreFieldConditionDTO scoreFieldConditionDTO : scoreRule){
                String attr = scoreFieldConditionDTO.getAttr();
                FieldAttrEntity field = explainMap.get(attr);
                if (field == null) {
                    continue;
                }
                Integer fieldType = field.getFieldType();
                // 字段名称
                String attrName = field.getAttrName();
                conditionStr.append(attrName).append("：");

                List<ScoreRuleConditionEntity> scoreConditionList = scoreFieldConditionDTO.getScoreConditionList();
                if(CollectionsUtil.isNotEmpty(scoreConditionList)){
                    for(ScoreRuleConditionEntity scoreRuleConditionEntity : scoreConditionList){
                        String symbol = scoreRuleConditionEntity.getSymbol();
                        ConditionEnum conditionEnum = ConditionEnum.getConditionEnum(symbol);
                        if (conditionEnum == null) {
                            continue;
                        }
                        // 条件名称
                        String condition = conditionEnum.getMemo();
                        // 范围取值区间
                        List<Object> value = scoreRuleConditionEntity.getValue();
                        String valueStr = null;
                        if(CollectionsUtil.isNotEmpty(value)){
                            if (Objects.equals(fieldType, FieldTypeEnum.COMBO.getType())
                                    ||Objects.equals(fieldType, FieldTypeEnum.RADIO_GROUP.getType())
                                    || Objects.equals(fieldType, FieldTypeEnum.CHECKBOX_GROUP.getType())
                                    || Objects.equals(fieldType, FieldTypeEnum.COMBO_CHECK.getType())) {
                                List<String> labelNames = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                                for (ItemPoJo itemPoJo : field.getItems()) {
                                    Object itemValue = itemPoJo.getValue();
                                    if (Objects.nonNull(itemValue)) {
                                        if(value.contains(itemValue)){
                                            labelNames.add(itemPoJo.getText());
                                        }
                                    }
                                }
                                valueStr = StringUtils.join(labelNames, "，");
                            } else if(FieldTypeEnum.LABEL.getType().equals(fieldType)){
                                List<Long> labelIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                                List<String> labelNameIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

                                value.forEach(item -> labelIdIn.add(Long.valueOf(item.toString())));
                                List<LabelEntity> labelEntityList = labelModel.getByLabelIds(labelIdIn, corpid);
                                labelEntityList.forEach(labelEntity -> labelNameIn.add(labelEntity.getName()));
                                valueStr = StringUtils.join(labelNameIn, "，");
                            } else if(FieldTypeEnum.DATETIME.getType().equals(fieldType) || FieldTypeEnum.ADDTIME.getType().equals(fieldType) ){
                                List<String> timeStrIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                                value.forEach(item -> timeStrIn.add(DateUtil.getString(Integer.valueOf(item.toString()), DateUtil.SDFDate)));
                                valueStr = StringUtils.join(timeStrIn, "，");
                            } else {
                                valueStr = StringUtils.join(value, "，");
                            }
                        }
                        ScoreOperationEntity scoreOperation = scoreRuleConditionEntity.getScoreOperation();
                        // 评分变化名称
                        String name = scoreOperation.getName();
                        // 评分变化数值
                        Double scoreValue = scoreOperation.getValue();

                        conditionStr.append(condition);
                        if(valueStr != null){
                            conditionStr.append("'").append(valueStr).append("'").append("；");
                        }
                        String score = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_SCORE_FIELD));
                        String scoreCode = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_SCORE_SCORE_RULE));
                        conditionStr.append(score).append(name).append(scoreValue).append(scoreCode).append("；");
                    }
                }
            }
        }
        return conditionStr.toString();
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseVO enableScoreRule(ScoreRuleEnableDTO scoreRuleEnableDTO) throws XbbException {
        Long dataId = scoreRuleEnableDTO.getDataId();
        Long formId = scoreRuleEnableDTO.getFormId();
        String corpid = scoreRuleEnableDTO.getCorpid();
        Integer enable = scoreRuleEnableDTO.getEnable();
        String loginUserName = scoreRuleEnableDTO.getLoginUserName();
        List<ScoreRuleEntity> scoreRuleEntityList = scoreRuleHelp.getAllScoreRuleByFormId(formId, corpid);
        //校验只能启用一个规则
        scoreRuleHelp.verificationEnableRuleCount(dataId,enable,scoreRuleEntityList);
        ScoreRuleEntity scoreRuleEntity = scoreRuleEntityList.stream().filter(item -> Objects.equals(item.getId(), dataId)).findFirst().get();
        scoreRuleEntity.setEnable(enable);
        scoreRuleModel.update(scoreRuleEntity);
        //刷新缓存
        scoreRuleModel.setEnabledScoreRule2Redis(corpid,formId,enable);
        //操作日志
        Runnable runnable = () -> {
            try {
                OperateTypeEnum operateTypeEnum;
                String memo;
                // enable 为 1 ,表示用户点击的是启用规则
                if(Objects.equals(enable, BasicConstant.ONE)){
                    operateTypeEnum = OperateTypeEnum.ENABLE;
                    memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.SCORE_RULE_OPEN), loginUserName, scoreRuleEntity.getRuleName());
                } else {
                    operateTypeEnum = OperateTypeEnum.CLOSE;
                    memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.SCORE_RULE_CLOSE), loginUserName, scoreRuleEntity.getRuleName());
                }
                mongoLogHelp.buildLog(corpid, scoreRuleEnableDTO.getUserId(), loginUserName, OperateModuleTypeEnum.SCORE_RULE_SET, operateTypeEnum, scoreRuleEntity.getId().toString(), scoreRuleEntity.getRuleName(), memo, scoreRuleEnableDTO.getHttpHeader());
            } catch (XbbException e) {
                LOG.error("ScoreRuleServiceImpl enableScoreRule 异常信息{}",e.getMessage());
            }
        };
        logThreadPoolBeanConfig.sysLogThreadPool().execute(runnable);
        return new BaseVO();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseVO deleteScoreRule(ScoreRuleDeleteDTO scoreRuleDeleteDTO) throws XbbException {
        Long dataId = scoreRuleDeleteDTO.getDataId();
        String corpid = scoreRuleDeleteDTO.getCorpid();

        ScoreRuleEntity scoreRuleEntity = scoreRuleModel.getByKey(dataId, corpid);
        //数据不存在校验
        if(Objects.isNull(scoreRuleEntity)){
            throw new XbbException(ScoreErrorCodeEnum.API_ERROR_1200015, ScoreErrorCodeEnum.API_ERROR_1200015.getMsg());
        }
        String ruleName = scoreRuleEntity.getRuleName();
        //启用状态的不能删除
        if(ScoreRuleStateEnum.ENABLED.getCode().equals(scoreRuleEntity.getEnable())){
            throw new XbbException(ScoreErrorCodeEnum.API_ERROR_1200016, ScoreErrorCodeEnum.API_ERROR_1200016.getMsg());
        }
        scoreRuleModel.deleteByKey(dataId, corpid);

        //操作日志
        Runnable runnable = () -> {
            try {
                String loginUserName = scoreRuleDeleteDTO.getLoginUserName();
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_SCORE_RULE_DELETE), loginUserName, ruleName);

                OperateTypeEnum operateTypeEnum = OperateTypeEnum.DELETE;
                mongoLogHelp.buildLog(corpid, scoreRuleDeleteDTO.getUserId(), loginUserName, OperateModuleTypeEnum.SCORE_RULE_SET, operateTypeEnum, "", "", memo, scoreRuleDeleteDTO.getHttpHeader());
            } catch (XbbException e) {
                LOG.error("ScoreRuleServiceImpl deleteScoreRule 异常信息{}",e.getMessage());
            }
        };
        logThreadPoolBeanConfig.sysLogThreadPool().execute(runnable);
        return new BaseVO();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseVO repeatScoreRule(ScoreRuleRepeatDTO scoreRuleRepeatDTO) throws XbbException {
        Map<String, Object> params = new HashMap<>(4);
        params.put("corpid", scoreRuleRepeatDTO.getCorpid());
        params.put("formId", scoreRuleRepeatDTO.getFormId());
        params.put("ruleName", scoreRuleRepeatDTO.getRuleName());
        params.put("del", 0);
        List<ScoreRuleEntity> entitys = scoreRuleModel.findEntitys(params);
        if(CollectionsUtil.isNotEmpty(entitys)){
            throw new XbbException(ScoreErrorCodeEnum.API_ERROR_1200007,ScoreErrorCodeEnum.API_ERROR_1200007.getMsg());
        }
        return new BaseVO();
    }

    @Override
    public ConditionListVO getScoreRuleCondition(ConditionListDTO conditionListDTO) throws XbbException {
        ConditionListVO conditionListVO = new ConditionListVO();
        try {
            Class clazz = ScoreRuleConditionConstant.class;
            Field[] fields = clazz.getDeclaredFields();
            Map<String, List<ConditionClass>> conditionMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if(fields != null && fields.length > 0){
                for (Field field: fields) {
                    FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnumByAliasLowerCase(field.getName().toLowerCase());
                    if (fieldTypeEnum == null || field.isSynthetic()) {
                        continue;
                    }
                    List<ConditionClass> conditions = ScoreRuleHelp.getScoreRuleConditionList(fieldTypeEnum);
                    conditionMap.put(fieldTypeEnum.getType().toString(), conditions);
                }
            }
            conditionListVO.setConditionList(conditionMap);
        } catch (XbbException e) {
            LOG.error("condition数据库获取筛选条件列表出错", e);
            throw e;
        } catch (Exception e) {
            LOG.error("condition数据库获取筛选条件列表出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return conditionListVO;
    }

    /**
     * 判断该表单下是否有启用的评分规则
     * @param corpid
     * @param formId
     * @return
     * @throws XbbException
     */
    @Override
    public Boolean haveEnabledScoreRule(String corpid, Long formId) throws XbbException {
        return scoreRuleModel.haveEnabledScoreRule(corpid, formId);
    }

}
